package com.newbie.pet.wrap;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.data.domain.Sort.Direction.DESC;

/**
 * 类描述：分页对象
 *
 * @author zhangkailiang
 * @date 2020/5/23
 */
@ApiModel("分页参数")
@Data
@Accessors(chain = true)
public class IPage {
    /**
     * 总的条数
     */
    @ApiModelProperty(value = "总的条数,只读", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private Long totalNum = 0L;
    /**
     * 总的页数
     */
    @ApiModelProperty(value = "总的页数,只读", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private Integer totalPage = 1;
    /**
     * 每页显示条数，默认 1
     */
    @ApiModelProperty(value = "每页显示条数", example = "1")
    private Integer size = 1;
    /**
     * 当前页
     */
    @ApiModelProperty(value = "当前页", example = "1")
    private Integer current = 1;
    /**
     * 排序参数
     * direction: aes,desc
     * property: id,date,name
     */
    @ApiModelProperty(value = "排序参数")
    private List<ISort> sorts;

    @ApiModel("排序参数")
    @Data
    public static class ISort {
        @ApiModelProperty(value = "排序类型", example = "desc")
        private String direction;

        @ApiModelProperty(value = "排序参数", example = "createDate")
        private String property;
    }

    /**
     * 转换为Spring Pageable
     */
    public PageRequest toPage() {
        int offset = current - 1;
        if (sorts == null || sorts.size() == 0) {
            return PageRequest.of(offset, size);
        } else {
            return PageRequest.of(offset, size, Sort.by(toSort(sorts)));
        }
    }

    private List<Sort.Order> toSort(List<ISort> sorts) {
        return sorts.stream().map(sort -> {
            if (DESC.name().equalsIgnoreCase(sort.getDirection())) {
                return Sort.Order.desc(sort.getProperty());
            } else {
                return Sort.Order.asc(sort.getProperty());
            }
        }).collect(Collectors.toList());
    }
}
